<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/28/028
 * Time: 10:58
 */

namespace app\api\model;


use app\api\service\Token;
use app\lib\exception\MemberException;
use app\lib\exception\OrderException;
use think\Db;
use think\Exception;
use Des3\DES3;
use app\api\model\MemberRoleInfo as MemberRoleInfoModel;
use app\api\service\Order as OrderService;

class Member extends BaseModel {

    protected $hidden = ['update_time','delete_time', 'create_time', 'password', 'safe_password', 'salt', 'status'];

    /**
     * 关联实名认证信息
     * @return \think\model\relation\HasOne
     */
    public function certification() {
        return $this->hasOne('Certification');
    }

    /**
     * 管理店铺信息
     * @return \think\model\relation\HasOne
     */
    public function shop() {
        return $this->hasOne('Shop');
    }

    /**
     * 量体师
     * @return \think\model\relation\HasOne
     */
    public function patternMaster() {
        return $this->hasOne('PatternMaster')->where('status', 2);
    }

    /**
     * 管理用户个人信息
     * @return \think\model\relation\HasOne
     */
    public function memberRoleInfo() {
        return $this->hasOne('MemberRoleInfo');
    }

    /**
     * 管理用户个人信息
     * @return \think\model\relation\HasOne
     */
    public function memberFigureMeasureData() {
        return $this->hasOne('MemberFigureMeasureData');
    }

    /**
     * 通过token获取用户信息
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public static function info() {
        $uid = Token::getCurrentUid();
        $member = self::with(['certification', 'shop', 'memberRoleInfo', 'pattern_master', 'memberFigureMeasureData'])->find($uid);

        $order_num = OrderService::getOrderNum($uid);


        $member['order_num'] = $order_num;

        return $member;
    }

    /**
     * 通过username获取用户信息
     * @param $username
     * @return null|\think\Model
     */
    public static function getMemberByUsername($username) {
        $member = self::get(['username' => $username]);
        return $member;
    }

    /**
     * 注册新用户
     * @param $mobile
     * @param $password
     * @return static
     * @throws MemberException
     */
    public static function register($mobile, $password) {

        // 组装注册用户数据
        $data['username'] = $mobile;

        // 生成密码加盐字符串
        $salt = getRandChar(6);
        $data['salt'] = $salt;
        $data['password'] = md5($password . $salt) . '123456';

        $data['last_login_time'] = time(); // 初始化登录时间
        // 启动事务
        Db::startTrans();
        try {
            $member = self::create($data);
            // 创建一条基本信息记录
            $member_role_info = ['member_id' => $member['id'],'nickname' => 'eybs-' . $member['id']];
            MemberRoleInfoModel::create($member_role_info);
            Db::commit();
        } catch (Exception $e) {
            throw new MemberException([
                'msg' => '注册新用户失败！错误原因：' . $e->getMessage(),
                'errorCode' => 30005
            ]);
        }

        return $member;
    }

    /**
     * 赠送衣币给好友
     * @param $username
     * @param $clothes_money
     * @return bool
     * @throws Exception
     * @throws MemberException
     */
    public static function giveClothesMoney($username, $clothes_money) {
        $uid = Token::getCurrentUid();
        // 检查收款用户是否存在
        $payee = self::get(['username' => $username]);
        if (!$payee) {
            throw new MemberException([
                'msg' => '收款帐号不存在！',
                'errorCode' => 30003
            ]);
        }

        $member = self::get(['id' => $uid]);
        if ($clothes_money > $member['clothes_money_recharge']) {
            throw new MemberException([
                'msg' => '账户可赠送衣币余额不足！',
                'errorCode' => 30004
            ]);
        }
        Db::startTrans();
        try {
            $payee->setInc('clothes_money_recharge', $clothes_money);
            MemberBill::add_member_bill($payee['id'], $clothes_money, '好友'.$member['username'].'赠送衣币', 5, '', '',  '衣币赠送', 2);
            $member->setDec('clothes_money_recharge', $clothes_money);
            MemberBill::add_member_bill($uid, $clothes_money, '赠送衣币给好友' . $username, 6, '', '',  '赠送衣币', 2);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }

        return true;
    }

    /**
     * 设置安全密码
     * @param $safe_password
     * @param $mobile
     * @throws MemberException
     */
    public static function setSafePassword($safe_password, $mobile) {
        $uid = Token::getCurrentUid();

        $member = model('member')->get(['id' => $uid, 'username' => $mobile]);
        if (!$member) {
            throw new MemberException();
        }

//        $des = new DES3();
//        $safe_password = $des->decrypt($safe_password);

        $safe_password  .= $member['salt'];
        $safe_password = md5($safe_password);
        $member->save(['safe_password' => $safe_password]);

        // 设置成功 清除错误记录（解锁）
        SafePasswordErrorLog::delete_log($uid);
    }

    /**
     * 获取用户团队信息
     * @return array
     */
    public static function memberTeam() {
        $uid = Token::getCurrentUid();

        $member = model('member')->get(['id' => $uid]);
        $teams = self::with('memberRoleInfo')->where(['parent_id' => $uid])->order('id desc')->select();
        foreach ($teams as $v) {
            $v->create_time = $v->getData('create_time');
            $v->visible(['create_time', 'member_role_info'])->member_role_info->visible(['nickname', 'headimgurl']);
        }
        return [
            'teams_count' => count($teams),
            'qr_code' => get_img_url($member['wx_qr_code']),
            'teams' => $teams
        ];
    }

    /**
     * 使用衣币支付订单时，扣除相应的衣币
     * @param $price
     * @param $member_id
     * @return bool
     * @throws OrderException
     */
    public static function clothesPayOrder($price, $member_id) {
        $member = self::get($member_id);

        if (($member->clothes_money_recharge + $member->clothes_money_donate) < $price) {
            throw new OrderException([
                'msg' => '账户衣币余额不足',
                'errorCode' => 30007
            ]);
        }

        if ($member->clothes_money_recharge >= $price) {
            $member->setDec('clothes_money_recharge', $price);
        } else {
            $clothes_money_donate = $price - $member->clothes_money_recharge;
            $member->save(['clothes_money_recharg' => 0]);
            $member->setDec('clothes_money_donate', $clothes_money_donate);
        }
        return true;
    }
}